<template>
  <div class="create-field-module">
    <div v-loading="isLoading" class="field-form">
      <div :style="{maxHeight: maxHeight+'px'}" class="field-scroll-container">
        <el-form ref="editFieldForm" :model="dataForm" :rules="dataForm.isFx ? formRules : noFormulaRules" :validate-on-rule-change="false" label-position="left" class="el-form-box-left" label-width="80px">
          <div class="form">
            <el-form-item label="字段名称" prop="name" class="name" style="margin-bottom: 24px">
              <el-input
                v-model.trim="dataForm.name"
                :disabled="!isCreate"
                maxlength="50"
                placeholder="请填写字段名称"
                name="name"
                type="text"/>
            </el-form-item>
            <el-form-item label="字段分类" prop="categoryId" class="client-type" style="margin-bottom: 24px">
              <el-select v-model="dataForm.categoryId" name="categoryId" popper-class="global-select-down" @change="categoryChange">
                <el-option label="请选择" value="" />
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="公式设置" prop="isFx" style="margin-bottom: 16px">
              <el-switch
                v-model="dataForm.isFx"/>
            </el-form-item>
            <div v-if="dataForm.isFx" class="formula-set-wrap" >
              <div class="quote-container">
                <div class="title">公式</div>
                <div class="quote-list" style="margin-bottom: 32px">
                  <div :class="{'active': formulaOption.isFocus}" class="formula-option" @click.stop="toFocus(formulaOption)" >
                    <el-scrollbar ref="formulaScrollbar">
                      <div class="formula-option-wrap">
                        <div
                          v-for="(tag, index) in formulaOption.options"
                          :key="index"
                          class="formula-option-tag"
                          @click.stop="deleteFormula(formulaOption, index)">{{ tag.name }}</div>
                      </div>

                    </el-scrollbar>
                  </div>
                </div>
                <div class="title">数据引用</div>
                <div class="quote-list">
                  <div class="quote-title">字段</div>
                  <div class="quote-input">
                    <!-- <el-select v-model="quoteField" value-key="name" class="filter-120" name="filterField" @change="fieldOptionsChange">
                    <el-option label="请选择" value="" />
                    <el-option
                      v-for="item in fieldOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item"/>
                  </el-select> -->
                    <el-cascader
                      v-model="quoteAllField"
                      :options="fieldOptions"
                      :props="{
                        value: 'name',
                        label: 'name',
                        children: 'fieldInfo'
                      }"
                      placeholder="选择字段"
                      class="filterableSelect"
                      filterable
                      clearable
                      @change="filedSelect" />
                  </div>
                  <el-button type="primary" size="small" class="quote-btn" @click="quoteFieldFun({name: quoteField.name, id: quoteField.id})">引用</el-button>
                </div>
                <div class="quote-list">
                  <div class="quote-title">数值</div>
                  <div class="quote-input">
                    <el-input :value="quoteValue" placeholder="请输入数字，可输入小数点" type="text" @input="keyupEvent" />
                  </div>
                  <el-button type="primary" size="small" class="quote-btn" @click="quoteFun({name: quoteValue, id: quoteValue * -1}, 'clearQuoteValue')">引用</el-button>
                </div>
                <div class="quote-list" style="margin-bottom: 32px">
                  <div class="quote-title" style="margin-right: 12px;">计算元素</div>
                  <div
                    v-for="(item, index) in mathTag"
                    :key="index"
                    class="quote-tag"
                    @click="quoteFun(item)"
                  >{{ item.name }}</div>
                </div>
                <div class="title">条件</div>
                <div class="quote-list">
                  <div class="select-sort no-lable">
                    <el-form-item class="condition-item" label="" label-width="0px" prop="conditionFirst">
                      <el-select
                        v-model="dataForm.conditionFirst"
                        value-key="name"
                        placeholder="请选择"
                        name="conditionFirst"
                        popper-class="global-select-down"
                        @change="basicsConditionChange">
                        <el-option label="请选择" value="" />
                        <el-option
                          v-for="(item, index) in fieldConditionItems"
                          :key="index"
                          :label="item.name"
                          :value="item.name" />
                      </el-select>
                    </el-form-item>
                    <el-form-item class="condition-item" label="" label-width="0px" prop="conditionSecond">
                      <el-select
                        v-model="dataForm.conditionSecond"
                        popper-class="global-select-down"
                        placeholder="请选择"
                        name="conditionSecond">
                        <el-option label="请选择" value="" />
                        <el-option
                          v-for="(item, index) in computeOption"
                          :key="index"
                          :label="item.name"
                          :value="item.name" />
                      </el-select>
                    </el-form-item>
                    <el-form-item class="condition-item" label="" label-width="0px" prop="conditonThird">
                      <!-- <el-select
                      v-model="dataForm.conditonThird"
                      value-key="name"
                      placeholder="请选择"
                      name="conditonThird">
                      <el-option label="请选择" value="" />
                      <el-option
                        v-for="item in detailOpts"
                        :key="item.id"
                        :label="item.name"
                        :value="item.name" />
                    </el-select> -->
                      <el-autocomplete
                        v-model="dataForm.conditonThird"
                        :disabled="dataForm.conditionFirst === ''"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入内容"
                        @select="handleConditionSearchSelect"
                      />
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <div class="dialog-footer" style="margin-top:20px;">
        <el-button :loading="opeatorLoading" class="ok" type="primary" @click="handelOk">保存</el-button>
        <el-button class="cancel cancel-btn-style" @click="cancleFun">取消</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { getFieldDetail, editField, addField, searchCondition } from '@/api/fieldManage';
import { mapState } from 'vuex';
import { numerical } from '@/utils/numFormat';
export default {
  name: 'AddFieldModule',
  props: {
    maxHeight: {
      type: Number | String,
      default: ''
    }
  },
  data() {
    return {
      isAggregation: false,
      isLoading: false,
      opeatorLoading: false,
      mathTag: [
        { name: '×', id: -1 },
        { name: '÷', id: -1 },
        { name: '+', id: -1 },
        { name: '-', id: -1 },
        { name: '(', id: -3 },
        { name: ')', id: -3 },
        { name: 'avg', id: -2 },
        { name: '∑', id: -2 },
        { name: '△', id: -2 } // 总数
      ],
      // fieldOptions: this.$store.state.options.fieldItems,
      detailData: null,
      formulaOption: {
        options: [],
        name: '',
        isFocus: false
      },
      detailOpts: [],
      cascaderValue: [],
      antiShakeTime: 0, // 防抖时间
      variableIdList: [], // 公式中出现的变量
      variableNameList: [],
      quoteAllField: '',
      dataForm: {
        name: '',
        categoryId: '',
        isFx: false,
        conditionFirst: '',
        conditionSecond: '',
        conditonThird: ''
      },
      formRules: {
        name: [{ required: true, trigger: 'blur, change', message: '请填写字段名称' }],
        categoryId: [{ required: true, trigger: 'change', message: '请选择字段分类' }],
        isFx: [{ required: true }],
        conditionFirst: [{ required: false, trigger: 'change', message: '请选择内容' }],
        conditionSecond: [{ required: false, trigger: 'change', message: '请选择内容' }],
        conditonThird: [{ required: false, trigger: 'change', message: '请选择内容' }]
      },
      noFormulaRules: {
        name: [{ required: true, trigger: 'blur, change', message: '请填写字段名称' }],
        categoryId: [{ required: true, trigger: 'change', message: '请选择字段分类' }],
        isFx: [{ required: true }]
      },
      quoteField: '',
      quoteValue: '',
      isCreate: true,
      fieldInfo: null,
      isBaseFx: false // 当前所选字段是否为基础字段
    };
  },
  computed: {
    ...mapState({
      'fieldListCache': state => state.options.fieldList,
      'computeOption': state => state.options.computeOperates,
      'conditionOption': state => state.options.collectOptions,
      'categoryList': state => state.options.fieldCategorys,
      'fieldConditionItems': state => state.options.fieldConditionItems
    }),
    fieldOptions() {
      const targetArr = [];
      this.fieldListCache.forEach(e => {
        const parentParams = { id: e.id, name: e.name, fieldInfo: [] };
        e.fieldInfo.forEach(item => {
          if (item.name !== this.dataForm.name) {
            parentParams.fieldInfo.push(item);
          }
        });
        targetArr.push(parentParams);
      });
      return targetArr;
    }
  },
  created() {
    this.$store.dispatch('GetFieldConditionItems'); // 获取字段列表
    this.$store.dispatch('GetComputeOperates'); // 获取运算操作符 computeOption
    window.removeReadOnly();
  },
  methods: {
    // 滚动条置底
    scrollBottom() {
      const scrollElement = this.$refs['formulaScrollbar'].$refs['wrap'];
      this.$nextTick(() => {
        scrollElement.scrollTop = scrollElement.scrollHeight;
      });
    },
    keyupEvent(value) {
      const str = numerical(value, 5, 9);
      this.quoteValue = str;
    },
    // 条件搜索逻辑
    async querySearchAsync(queryString, cb) {
      if (this.dataForm.conditionFirst === '销售额') cb([]);
      const params = {
        'conditionItem': this.dataForm.conditionFirst,
        'keyword': queryString
      };
      const res = await searchCondition(params);
      let result = [];
      if (res.data) {
        result = res.data.map(name => {
          return {
            'value': name
          };
        });
      }
      cb(result);
    },
    // 条件搜索第三项 选择后的操作
    handleConditionSearchSelect() {

    },
    // 字段选择改变
    fieldOptionsChange(item) {
      this.isBaseFx = item.isFx === 1;
    },
    // 确定
    handelOk() {
      var timestamp = new Date().getTime();
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      this.$refs['editFieldForm'].validate((valid) => {
        if (valid && this.formulaOption.options.length > 0 || !this.dataForm.isFx && valid) {
          let params;
          if (this.dataForm.isFx) {
            let formula = '';
            this.formulaOption.options.forEach(item => {
              if (item.postName) {
                formula += item.postName;
              } else {
                formula += item.name;
              }
            });
            params = {
              name: this.dataForm.name,
              categoryId: this.dataForm.categoryId,
              isFx: 2,
              formula,
              formulaObj: this.formulaOption.options,
              variate: this.variableNameList.join(','),
              fieldConditionItem: this.dataForm.conditionFirst,
              fieldConditionOption: this.dataForm.conditionSecond,
              fieldConditionValue: this.dataForm.conditonThird,
              variateIdList: this.variableIdList
            };
          } else {
            params = {
              name: this.dataForm.name,
              categoryId: this.dataForm.categoryId,
              isFx: 1
            };
          }
          this.opeatorLoading = true;
          if (this.isCreate) {
            addField(params).then(res => {
              this.opeatorLoading = false;
              if (res.code === 200) {
                this.$emit('success');
                this.$message({
                  type: 'success',
                  message: '新建成功'
                });
              } else {
                const message = res.message ? res.message : '创建失败';
                this.$message({
                  type: 'error',
                  message: message
                });
              }
            });
          } else {
            params.categoryId = this.dataForm.categoryId;
            params.id = this.fieldInfo.id;
            editField(params).then(res => {
              this.opeatorLoading = false;
              if (res.code === 200) {
                this.$emit('success');
                this.$message({
                  type: 'success',
                  message: '编辑成功'
                });
              } else {
                const message = res.message ? res.message : '编辑失败';
                this.$message({
                  type: 'error',
                  message: message
                });
              }
            });
          }
        } else {
          this.$message({ type: 'warning', message: '请正确填写字段内容' });
          return false;
        }
      });
    },
    filedSelect(item) {
      this.fieldListCache.forEach(i => {
        if (i.name === item[0]) {
          i.fieldInfo.forEach(j => {
            if (j.name === item[1]) {
              this.quoteField = j;
            }
          });
        }
      });
      this.isBaseFx = this.quoteField.isFx === 1;
    },
    // 取消
    cancleFun() {
      this.$emit('cancle');
    },
    basicsConditionChange(value) {
      if (value === '') {
        this.dataForm.conditionSecond = '';
        this.dataForm.conditonThird = '';
      }
    },
    detailConditon(name) {
      const index = this.lastCondition(name);
      this.detailOpts = this.conditionOption.conditionOptions.condition[index].options;
    },
    toFocus(item) {
      item.isFocus = true;
    },
    quoteFun(item, clear) {
      const value = item.name;
      if (this.isAggregation) {
        if ('∑avg()'.indexOf(value) >= 0) {
          this.$message({ type: 'warning', message: '计算元素∑、avg后面不能为∑,avg,(,)' });
          return;
        }
        this.isAggregation = false;
      }
      if (value === '∑' || value === 'avg') {
        this.isAggregation = true;
      }
      if (!value || value === '') return;
      this.formulaOption.options.push(item);
      this.scrollBottom();
      if (clear === 'clearQuoteValue') {
        this.quoteValue = '';
      }
      if (clear === 'clearquoteField') {
        this.quoteField = '';
        this.cascaderValue = [];
      }
    },
    quoteFieldFun(item, clear) {
      const value = item.name;
      if (this.isAggregation) {
        if (!this.isBaseFx) {
          this.$message({ type: 'warning', message: '计算元素∑、avg后面应为基础字段' });
          return;
        }
        this.isAggregation = false;
      }
      if (!value || value === '') return;
      this.quoteAllField = '';
      this.quoteField = '';
      item.postName = `"${item.name}"`;
      this.formulaOption.options.push(item);
      this.variableIdList.push(item.id);
      this.variableNameList.push(`"${item.name}"`);
      this.scrollBottom();
      if (clear === 'clearQuoteValue') {
        this.quoteValue = '';
      }
    },
    deleteFormula(item, index) {
      const name = item.options[index].name;
      const id = item.options[index].id;
      const postName = `"${name}"`;
      item.options.splice(index, 1);
      const fronIndex = index - 1 >= 0 ? index - 1 : 0;
      if (item.options.length > 0 && index >= 0 && 'avg∑'.indexOf(item.options[fronIndex].name) >= 0 && this.judgeIsFx(item.options[index])) {
        this.deleteFormula(item, index);
      }
      if (item.options.length - 1 >= 0 && 'avg∑'.indexOf(item.options[item.options.length - 1].name) >= 0) {
        this.isAggregation = true;
      } else {
        this.isAggregation = false;
      }
      if (id >= 0) {
        const deleteIdIndex = this.variableIdList.indexOf(id);
        if (deleteIdIndex >= 0) this.variableIdList.splice(deleteIdIndex, 1);
        const deleteNameIndex = this.variableNameList.indexOf(postName);
        if (deleteNameIndex >= 0) this.variableNameList.splice(deleteNameIndex, 1);
      }
    },
    // 判断字段是否为聚合字段
    judgeIsFx(item) {
      if (!item) return;
      const id = item.id;
      let isFx = false;
      this.fieldOptions.forEach(i => {
        i.fieldInfo.forEach(j => {
          if (j.id === id && j.isFx === 2) {
            isFx = true;
          }
        });
      });
      return isFx;
    },
    // 如果是编辑字段 则获取字段详情
    getFieldDetail(id) {
      if (this.isLoading) return;
      const params = {
        fieldId: id
      };
      this.isLoading = true;
      this.$refs['editFieldForm'].resetFields();
      getFieldDetail(params).then(res => {
        const data = res.data;
        this.isLoading = false;
        if (data) {
          this.detailData = data;
          this.dataForm.name = data.name;
          this.dataForm.categoryId = data.categoryId;
          this.dataForm.isFx = data.isFx === 2;
          if (this.dataForm.isFx) {
            this.dataForm.conditionFirst = data.fieldConditionItem;
            this.dataForm.conditionSecond = data.fieldConditionOption;
            this.dataForm.conditonThird = data.fieldConditionItemValue;
            this.formulaOption.options = data.formulaObject;
            this.detailConditon(this.dataForm.conditionFirst);
            if (data.formulaObject) {
              this.variableNameList = data.formulaObject.filter(item => item.postName !== null).map(item => item.postName);
              this.variableIdList = data.formulaObject.filter(item => item.postName !== null).map(item => item.id);
              if (data.formulaObject && data.formulaObject.length > 0) {
                if ('avg∑'.indexOf(data.formulaObject[data.formulaObject.length - 1].name) >= 0) {
                  this.isAggregation = true;
                }
              }
            }
          }
        }
      }).catch(e => {
        console.error(e);
        this.isLoading = false;
        const errMsg = typeof e === 'object' ? e.message : e;
        this.$emit('onErrorExport', errMsg || '请求失败');
      });
    },
    // 根据首个筛选条件名称制定第三筛选条件
    lastCondition(name) {
      let index = 0;
      const conditions = this.conditionOption.conditionOptions.condition;
      conditions.forEach((res, i) => {
        if (res.name === name) {
          index = i;
        }
      });
      return index;
    },
    // 清除表单数据
    clear() {
      this.isAggregation = false;
      this.$refs['editFieldForm'].resetFields();
      this.variableIdList = [];// 公式中出现的变量
      this.variableNameList = [];
      this.quoteField = '';
      this.quoteAllField = '';
      this.quoteValue = '';
      this.isCreate = true;
      this.formulaOption.options = [];
    },
    // 字段分类改变
    categoryChange(value) {
      // console.log(value);
      // this.quoteField = '';
    }
  }
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
// .create-field-module {
//   .one-cell {
//     display: flex;
//     .name {
//       margin-right: 56px;
//     }
//   }
// }
.formula-set-wrap {
  display: flex;
  flex-direction: column;
  width: 480px;
  padding: 24px;
  margin: 0 56px 10px 85px;
  border-radius: 4px;
  border: 1px solid rgba(221,221,221,1);
  .quote-container {
    // margin-top: 32px;
    .title {
      font-size:14px;
      line-height: 1;
      font-family:PingFangSC-Medium,PingFang SC;
      font-weight:500;
      color:rgba(51,51,51,1);
    }
    .quote-list {
      margin-top: 16px;
      display: flex;
      align-items: center;
      .quote-title {
        margin-right: 40px;
        font-size:14px;
        font-family:PingFangSC-Regular,PingFang SC;
        font-weight:400;
        color:rgba(102,102,102,1);
      }
      .quote-input {
        width: 240px;
        margin-right: 16px;
        & ::v-deep {
          .el-input__inner {
            width: 240px;
          }
        }
      }
      .quote-tag {
        width:24px;
        height:24px;
        background:rgba(239,243,251,1);
        border-radius:4px;
        color: #406EFF;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;
        cursor: pointer;
        font-size: 12px;
      }
    }
    .save-field {
      display: flex;
      align-items: center;
      margin-top: 32px;
      margin-bottom: 30px;
      .text {
        font-size:14px;
        font-family:PingFangSC-Medium,PingFang SC;
        font-weight:500;
        color:rgba(51,51,51,1);
        line-height:14px;
        margin-right: 12px;
      }
    }
  }
  .formula-option::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
  .formula-option {
    min-width:240px;
    min-height:32px;
    max-height: 113px;
    border-radius:4px;
    border:1px solid rgba(221,221,221,1);
    padding-bottom: 3px;
    cursor: pointer;
    display: flex;
    overflow: hidden;
    // align-items: center;
    &.active {
      border: 1px solid #406EFF;
    }
    .formula-option-wrap {
      display: flex;
      flex-wrap: wrap;
      // padding-top: 3px;
      // height: 29px;
      // width: 100%;
      // overflow: auto;
    }
    .formula-option-tag {
      padding: 0 8px;
      height:24px;
      background:rgba(239,243,251,1);
      border-radius:4px;
      color: #406EFF;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      cursor: pointer;
      font-size: 12px;
      margin: 3px 4px 0 4px;
      white-space: nowrap;
    }
  }
}
.field-scroll-container {
  @include scrollBar();
}
</style>
<style lang="scss">
.create-field-module {
  margin-top: 24px;
  // max-height: 500px;
  // overflow-y: scroll;
  @include scrollBar();
  .el-input__inner {
    height: 32px;
    line-height: 30px;
    width: 240px;
  }
  .el-form {
    .el-form-item {
      .el-form-item__label {
        font-size: 14px !important;
      }
      .el-input__icon {
        line-height: 24px;
      }
      // .el-input__inner {
      //   height: 30px;
      //   line-height: 30px;
      //   width: 240px;
      // }
    }
    .contact-list {
      margin-bottom: 16px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .add-btn {
      button {
        width: 501px;
        background-color: #f4f4f4;
        border: 1px dashed #e0e0e0;
        color: #777;
        .add-img {
          margin-right: 8px;
        }
      }
    }
  }
  .flex {
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }
  .select-sort {
    display: inline-block;
    display: flex;
    .el-input {
      width: 120px !important;
      margin-left: 19px;
    }
    &.no-lable {
      .el-input {
        width: 120px !important;
        margin-left: 0px;
      }
      .condition-item {
        margin-right: 19px;
        el-form-item__content {
          margin-left: 0;
        }
      }
    }
    .el-input__inner {
      width: 120px !important;
    }
  }
}
.formula-option {
  .el-scrollbar__wrap {
    overflow-x: hidden;
    margin-bottom: 0px !important;
  }
}
</style>
